<template>
  <el-card title="按钮埋点演示" style="margin-top: 20px">
    <el-alert
      v-if="!mockTracker"
      title="模拟追踪器未启用"
      description="启用模拟追踪器可在页面上查看埋点事件。在实际环境中，埋点事件将发送到服务器。"
      type="warning"
      :closable="false"
      show-icon
      style="margin-bottom: 16px"
    >
      <template #action>
        <el-button size="small" type="primary" @click="toggleMockTracker">
          启用模拟追踪器
        </el-button>
      </template>
    </el-alert>
    
    <el-alert
      v-else
      title="模拟追踪器已启用"
      description="现在可以在下方查看埋点事件日志。在实际环境中，这些事件会发送到服务器进行统计分析。"
      type="success"
      :closable="false"
      show-icon
      style="margin-bottom: 16px"
    >
      <template #action>
        <el-button size="small" @click="toggleMockTracker">
          关闭模拟追踪器
        </el-button>
      </template>
    </el-alert>
    
    <h4>选项表单演示</h4>
    <p>此演示展示了如何在不同交互场景中应用埋点</p>
    
    <div class="demo-form">
      <el-radio-group v-model="selectedOption">
        <el-radio label="option1">选项一</el-radio>
        <el-radio label="option2">选项二</el-radio>
        <el-radio label="option3">选项三</el-radio>
      </el-radio-group>
      
      <el-divider />
      
      <el-space direction="vertical" style="width: 100%">
        <h5>1. 使用TrackableButton组件（推荐）</h5>
        <el-space>
          <TrackableButton 
            type="primary"
            :icon="Promotion"
            :tracking-data="{
              buttonName: 'submit_button',
              pageName: 'demo_page',
              extraData: { method: 'trackable_button', option: selectedOption }
            }"
            @click="() => handleSubmit(true)"
          >
            提交表单
          </TrackableButton>
          
          <TrackableButton 
            type="danger"
            :icon="Delete"
            :tracking-data="{
              buttonName: 'delete_button',
              pageName: 'demo_page',
              extraData: { method: 'trackable_button', option: selectedOption }
            }"
            @click="handleDelete"
          >
            删除项目
          </TrackableButton>
        </el-space>
        
        <el-divider />
        
        <h5>2. 使用Hook手动追踪（灵活）</h5>
        <el-space>
          <el-button type="primary" :icon="Edit" @click="handleNormalClick">
            普通按钮
          </el-button>
          
          <el-button 
            type="default" 
            :icon="VideoPlay"
            @click="() => handleSubmit(false)"
          >
            模拟失败
          </el-button>
        </el-space>
      </el-space>
    </div>
    
    <template v-if="mockTracker">
      <el-divider>埋点事件日志</el-divider>
      <div class="event-log">
        <div style="display: flex; justify-content: space-between; margin-bottom: 8px">
          <h5>事件记录 ({{ eventLog.length }})</h5>
          <el-button size="small" @click="clearEventLog">清空日志</el-button>
        </div>
        
        <div v-if="eventLog.length === 0" style="text-align: center; color: #999; padding: 40px">
          暂无埋点事件，点击上方按钮触发埋点
        </div>
        <div v-else class="event-list">
          <div 
            v-for="(event, index) in eventLog" 
            :key="index"
            class="event-item"
          >
            <div>
              <strong>{{ event.timestamp }}</strong> 
              {{ event.type === 'customData' ? '自定义数据' : `${event.category}/${event.action}/${event.label}` }}
            </div>
            <div style="font-size: 12px; color: #666; margin-top: 4px">
              <pre>{{ JSON.stringify(event.type === 'customData' ? event : event.customData, null, 2) }}</pre>
            </div>
          </div>
        </div>
      </div>
    </template>
    
    <el-divider />
    
    <p style="color: #999">
      <strong>提示：</strong> 在实际应用中，建议使用TrackableButton组件实现按钮埋点，这样可以将埋点逻辑与业务逻辑分离，降低耦合度，提高代码可维护性。
    </p>
  </el-card>
</template>

<script setup lang="ts">
import { ref, watch, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Promotion, Delete, Edit, VideoPlay } from '@element-plus/icons-vue'
import TrackableButton from '@/components/TrackableButton.vue'
import { useTracking } from '@/utils/useTracking'

const selectedOption = ref('option1')
const eventLog = ref<any[]>([])
const mockTracker = ref(false)
let originalTracker: any = null

// 使用埋点Hook
const { trackButtonClick, trackFormSubmit, trackUserAction } = useTracking()

// 模拟埋点追踪器
const createMockTracker = () => {
  originalTracker = (window as any).DevOpsBITracker
  
  ;(window as any).DevOpsBITracker = {
    trackEvent: (category: string, action: string, label: string, value: number, customData: any) => {
      const event = { 
        category, 
        action, 
        label, 
        value, 
        customData, 
        timestamp: new Date().toLocaleTimeString() 
      }
      eventLog.value = [...eventLog.value, event]
      console.log('模拟埋点事件', event)
    },
    trackCustomData: (customData: any) => {
      const event = { 
        type: 'customData', 
        ...customData, 
        timestamp: new Date().toLocaleTimeString() 
      }
      eventLog.value = [...eventLog.value, event]
      console.log('模拟自定义埋点事件', event)
    }
  }
}

const restoreTracker = () => {
  ;(window as any).DevOpsBITracker = originalTracker
}

watch(mockTracker, (enabled) => {
  if (enabled) {
    createMockTracker()
  } else {
    restoreTracker()
    eventLog.value = []
  }
})

onUnmounted(() => {
  if (mockTracker.value) {
    restoreTracker()
  }
})

const toggleMockTracker = () => {
  mockTracker.value = !mockTracker.value
}

const handleNormalClick = () => {
  ElMessage.success('普通按钮点击了')
  // 这里需要手动调用埋点函数
  trackButtonClick('normal_button', 'demo_page', { method: 'manual_tracking' })
}

const handleDelete = () => {
  ElMessage.warning('删除操作执行')
  trackUserAction('delete', 'demo_item', { itemType: 'demo', importance: 'high' })
}

const handleSubmit = (success: boolean) => {
  if (success) {
    ElMessage.success('表单提交成功')
    trackFormSubmit('demo_form', 'success', { formData: { option: selectedOption.value } })
  } else {
    ElMessage.error('表单提交失败')
    trackFormSubmit('demo_form', 'failure', { error: 'validation_failed' })
  }
}

const clearEventLog = () => {
  eventLog.value = []
}
</script>

<style scoped lang="scss">
.demo-form {
  h5 {
    margin: 16px 0 8px 0;
  }
}

.event-log {
  h5 {
    margin: 0;
  }
}

.event-list {
  max-height: 200px;
  overflow-y: auto;
  border: 1px solid #eee;
  padding: 8px;
  border-radius: 4px;
}

.event-item {
  margin-bottom: 8px;
  padding: 8px;
  background: #f5f5f5;
  border-radius: 4px;
  
  pre {
    margin: 4px 0 0 0;
    font-size: 12px;
  }
}
</style>
